package com.jd.pet.service.impl;

import com.jd.basic.exception.BusinessException;
import com.jd.basic.service.IBaiduAiAuditService;
import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.basic.util.*;
import com.jd.order.domain.OrderPetAcquisition;
import com.jd.order.mapper.OrderPetAcquisitionMapper;
import com.jd.org.domain.Employee;
import com.jd.org.domain.Shop;
import com.jd.org.mapper.EmployeeMapper;
import com.jd.org.mapper.ShopMapper;
import com.jd.pet.domain.Pet;
import com.jd.pet.domain.SearchMasterMsg;
import com.jd.pet.domain.SearchMasterMsgAuditLog;
import com.jd.pet.mapper.PetMapper;
import com.jd.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.jd.pet.mapper.SearchMasterMsgMapper;
import com.jd.pet.query.SearchMasterMsgQuery;
import com.jd.pet.service.ISearchMasterMsgService;
import com.jd.user.domain.Logininfo;
import com.jd.user.domain.User;
import com.jd.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private PetMapper petMapper;





    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        //        id        -   自增长
        //        name      -   来自页面
        //        age       -   来自页面
        //        gender    -   来自页面
        //        coat_color-   来自页面
        //        resources -   来自页面
        //        pet_type  -   来自页面
        //        price     -   来自页面
        //        address   -   来自页面
        //        state     -   来自实体默认值 //0表示待审核或驳回， 1表示已审核待处理，2表示处理成功，3拒
        //        title     -   来自页面
        //        user_id   -   谁发布的寻主消息 = 用户 = 登录了才能发布
        //        shop_id   -   获取最近的门店的id

        //1.获取登录人id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        searchMasterMsg.setUserId(user.getId());
        //2.将寻主消息添加到数据库
        searchMasterMsgMapper.save(searchMasterMsg);

        //3.百度ai智能审核
        Boolean boo1 = baiduAiAuditService.textAudit(searchMasterMsg.getTitle() + searchMasterMsg.getName());

        Boolean boo2 = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());

        //3.1审核成功
        if (boo1 && boo2){
            // 修改状态
            searchMasterMsg.setState(1);
            // 找到最近的店铺id
            List<Shop> shops = shopMapper.loadAll();
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            // 找到最近的店铺id
            if (nearestShop != null){
                searchMasterMsg.setShopId(nearestShop.getId());

            }
            // 更新数据库
            searchMasterMsgMapper.update(searchMasterMsg);

            // 添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(1);

            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.save(log);

            if (nearestShop != null){
                Employee employee = employeeMapper.loadByShopId(nearestShop.getId());
                System.out.println("你有新的订单，请尽快处理："+searchMasterMsg.getAddress());

            }

            return new AjaxResult();
        }else {
            //2.2.审核失败：修改寻主消息状态0 + 添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            //audit_id - 自动审核，没有添加审核人
            log.setState(0);//审核失败 - 驳回
            log.setNote("审核失败，内容非法");
            searchMasterMsgAuditLogMapper.save(log);
            //4.发送一条短信给门店管理员 - 通知去收宠物
            System.out.println("你有发布寻主消息未通过审核，请你重新修改信息！");

            return AjaxResult.me().setSuccess(false).setMsg("审核失败");


        }
    }

    @Override
    public PageList<SearchMasterMsg> userQuery(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 获取用户的id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());

        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 判断一个管理员是店铺管理员还是平台管理员
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if (employee.getShop_id() != null){
            query.setShopId(employee.getShop_id());
        }

        return super.queryPage(query);
    }


    @Override
    public void reject(Long id) {
        // 通过id将shopid为null
        searchMasterMsgMapper.updateShopId(id);
    }



    @Override
    public void accept(Map<String, String> map) {

        long msgId = Long.parseLong(map.get("msgId"));
        long handler = Long.parseLong(map.get("handler"));
        String note = map.get("note");
        // 1.校验改寻主消息是否已经在处理，报错
        OrderPetAcquisition order =  orderPetAcquisitionMapper.loadByMsgId(msgId);
        if (order != null && order.getState() == 0){
            throw new BusinessException("已经被接单，正在处理中");
        }

        // 2.生成宠物保存数据库
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = msg2Pet(msg);
        petMapper.save(pet);

        // 3.生成订单
        OrderPetAcquisition opa = createOrder(msg,pet,handler,note);
        orderPetAcquisitionMapper.save(opa);

        // 短信通知和邮件通知
        System.out.println("请到【"+msg.getAddress()+"】接宠物");


    }



    private Pet msg2Pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        // 市场价格
        pet.setType_id(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setState(0);
        pet.setShop_id(msg.getShopId());
        pet.setUser_id(msg.getUserId());
        pet.setSearch_master_msg_id(msg.getId());
        return pet;

    }


    private OrderPetAcquisition createOrder(SearchMasterMsg msg, Pet pet, long handler, String note) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(pet.getUser_id());
        order.setOrderSn(orderSn);
        order.setDigest(msg.getName()+"收购订单");
        Date date = new Date(System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000);
        order.setLastcomfirmtime(date);
        order.setPrice(msg.getPrice());

        order.setPetId(pet.getId());
        order.setUserId(pet.getUser_id());
        order.setShopId(pet.getShop_id());
        order.setAddress(msg.getAddress());
        order.setEmpId(handler);
        order.setSearchMasterMsgId(msg.getId());

        return order;
    }

}
